package com.zxmc.server.service.impl;


import com.alibaba.fastjson2.JSON;
import com.zxmc.common.context.BaseContext;
import com.zxmc.common.result.Result;
import com.zxmc.pojo.dto.UpdateChatHistoryDto;
import com.zxmc.pojo.entity.ReadingHistory;
import com.zxmc.pojo.entity.User;
import com.zxmc.pojo.vo.CommunicateVO;
import com.zxmc.server.service.ChatService;
import com.zxmc.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserService userService;
    @Override
    public List<CommunicateVO> list(String friendName) {
        String toUserName = userService.list().getUsername();
        String key1 = "chat:" +friendName+":"+toUserName+":*";
        String key2 = "chat:" + toUserName+":"+friendName + ":*";
        Set<String> keys = redisTemplate.keys(key1);
        keys.addAll(redisTemplate.keys(key2));
        List<CommunicateVO> communicateVOS = new ArrayList<>();
        if (!keys.isEmpty()) {
            for (String key : keys) {
                Object value = redisTemplate.opsForValue().get(key);
                if (value != null) {
                    // 使用 FastJSON 将 JSONObject 转换为 ReadingHistory 对象
                    CommunicateVO communicateVO = JSON.to(CommunicateVO.class, value);
                    communicateVOS.add(communicateVO);
                }
            }
        }
        // 按照 createTime 升序排序
        communicateVOS.sort(Comparator.comparing(CommunicateVO::getCreateTime));
        return communicateVOS;
    }
    public void update(UpdateChatHistoryDto updateChatHistoryDto) {
        String userName = updateChatHistoryDto.getUserName();
        String toUserName = userService.list().getUsername();
        String key1 = "chat:" + userName+":"+toUserName+":*";
        Set<String> keys = redisTemplate.keys(key1);
        if (!keys.isEmpty()) {
            for (String key : keys) {
                Object value = redisTemplate.opsForValue().get(key);
                if (value != null) {
                    // 使用 FastJSON 将 JSONObject 转换为 ReadingHistory 对象
                    CommunicateVO communicateVO = JSON.to(CommunicateVO.class, value);
                    communicateVO.setStatus(1);
                    updateRedisStringValue(key,communicateVO);

                }
            }
        }
    }

    @Override
    public void delete(User user) {
        // 生成键模式
        String keyPattern = "chat:" + user.getUsername() + ":*";
        String keyPattern1 = "chat:*:" + user.getUsername() + ":*";
        // 获取所有匹配的键
        Set<String> keys = redisTemplate.keys(keyPattern);
        Set<String> keys1 = redisTemplate.keys(keyPattern1);
        keys.addAll(keys1);
        if (!keys.isEmpty()) {
            // 删除所有匹配的键
            redisTemplate.delete(keys);
        }
    }

    // 定义一个方法用于修改 string 类型的值且不改变失效时间
    private void updateRedisStringValue(String key, Object newValue) {
        String jsonValue = JSON.toJSONString(newValue);
        redisTemplate.execute((RedisCallback<Object>) connection -> {
            // 执行 GETSET 命令
            byte[] rawKey = redisTemplate.getStringSerializer().serialize(key);
            byte[] rawValue = redisTemplate.getStringSerializer().serialize(jsonValue);
            if (rawKey != null) {
                if (rawValue != null) {
                    connection.getSet(rawKey, rawValue);
                }
            }
            return null;
        });
    }
}
